package com.eduagent.xwqeduagent.controller;

import cn.hutool.core.util.StrUtil;
import com.eduagent.xwqeduagent.api.GeneralImageEditing.api.GeneralImageEditingApi;
import com.eduagent.xwqeduagent.api.GeneralImageEditing.model.CreateImageSynthesisTaskResponse;
import com.eduagent.xwqeduagent.api.GeneralImageEditing.model.GetImageSynthesisTaskResponse;
import com.eduagent.xwqeduagent.api.PictureDoodlePainting.api.PictureDoodlePaintingApi;
import com.eduagent.xwqeduagent.api.PictureDoodlePainting.model.CreateDoodlePaintingTaskResponse;
import com.eduagent.xwqeduagent.api.PictureDoodlePainting.model.GetDoodlePaintingTaskResponse;
import com.eduagent.xwqeduagent.api.aliyunTextToImage.api.AliYunAiTextToImageApi;
import com.eduagent.xwqeduagent.api.aliyunTextToImage.model.CreateTextToImageTaskResponse;
import com.eduagent.xwqeduagent.api.aliyunTextToImage.model.GetTextToImageTaskResponse;
import com.eduagent.xwqeduagent.api.aliyunaiImageOutPaining.api.AliYunAiApi;
import com.eduagent.xwqeduagent.api.aliyunaiImageOutPaining.model.CreateOutPaintingTaskResponse;
import com.eduagent.xwqeduagent.api.aliyunaiImageOutPaining.model.GetOutPaintingTaskResponse;
import com.eduagent.xwqeduagent.api.aliyunaiReshapingImage.api.AliYunAiReshapingImageApi;
import com.eduagent.xwqeduagent.api.aliyunaiReshapingImage.model.CreateImageRestyleTaskResponse;
import com.eduagent.xwqeduagent.api.aliyunaiReshapingImage.model.GetImageRestyleTaskResponse;
import com.eduagent.xwqeduagent.common.BaseResponse;
import com.eduagent.xwqeduagent.common.ResultUtils;
import com.eduagent.xwqeduagent.exception.BusinessException;
import com.eduagent.xwqeduagent.exception.ErrorCode;
import com.eduagent.xwqeduagent.exception.ThrowUtils;
import com.eduagent.xwqeduagent.model.dto.CreateDoodlePaintingRequest;
import com.eduagent.xwqeduagent.model.dto.CreateGeneralImageEditingRequest;
import com.eduagent.xwqeduagent.model.dto.CreatePictureOutPaintingTaskRequest;
import com.eduagent.xwqeduagent.model.dto.CreatePictureTextToImageTaskRequest;
import com.eduagent.xwqeduagent.model.dto.PortraitStyleRemakeRequest;
import com.eduagent.xwqeduagent.service.PictureService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/picture")
public class PictureController {

    @Resource
    private PictureService pictureService;

    @Resource
    private AliYunAiApi aliYunAiApi;

    @Resource
    private AliYunAiTextToImageApi aliYunAiTextToImageApi;

    @Resource
    private AliYunAiReshapingImageApi aliYunAiReshapingImageApi;
    
    @Resource
    private GeneralImageEditingApi generalImageEditingApi;
    
    @Resource
    private PictureDoodlePaintingApi pictureDoodlePaintingApi;

    /**
     * 创建 AI 扩图任务
     */
    @PostMapping("/out_painting/create_task")
    public BaseResponse<CreateOutPaintingTaskResponse> createPictureOutPaintingTask(
            @RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest) {
        if (createPictureOutPaintingTaskRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        CreateOutPaintingTaskResponse response = pictureService.createPictureOutPaintingTask(createPictureOutPaintingTaskRequest);
        return ResultUtils.success(response);
    }

    /**
     * 查询 AI 扩图任务
     */
    @GetMapping("/out_painting/get_task")
    public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTask(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetOutPaintingTaskResponse task = aliYunAiApi.getOutPaintingTask(taskId);
        
        // 如果返回了错误码，需要检查任务是否失败
        if (task.getOutput() != null && "FAILED".equals(task.getOutput().getTaskStatus())) {
            // 任务失败的原因记录在错误码和错误信息中
            String errorCode = task.getOutput().getCode();
            String errorMsg = task.getOutput().getMessage();
            if (StrUtil.isNotBlank(errorCode)) {
                log.error("AI扩图任务失败，taskId: {}, code: {}, message: {}", 
                        taskId, errorCode, errorMsg);
            }
        }
        
        return ResultUtils.success(task);
    }

    /**
     * 创建 AI 文字生成图片任务
     */
    @PostMapping("/text_to_image/create_task")
    public BaseResponse<CreateTextToImageTaskResponse> createPictureTextToImageTask(
            @RequestBody CreatePictureTextToImageTaskRequest createPictureTextToImageTaskRequest) {
        if (createPictureTextToImageTaskRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        CreateTextToImageTaskResponse response = pictureService.createTextToImageTask(createPictureTextToImageTaskRequest);
        return ResultUtils.success(response);
    }

    /**
     * 查询 AI 文字生成图片任务
     */
    @GetMapping("/text_to_image/get_task")
    public BaseResponse<GetTextToImageTaskResponse> getPictureTextToImageTask(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetTextToImageTaskResponse textToImageTask = aliYunAiTextToImageApi.getTextToImageTask(taskId);
        return ResultUtils.success(textToImageTask);
    }

    /**
     * 创建 AI 人像风格重塑任务
     */
    @PostMapping("/image_restyle/create_task")
    public BaseResponse<CreateImageRestyleTaskResponse> createImageRestyleTask(
            @RequestBody PortraitStyleRemakeRequest portraitStyleRemakeRequest,
            HttpServletRequest request) {
        if (portraitStyleRemakeRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        CreateImageRestyleTaskResponse response = pictureService.createImageRestyleTask(portraitStyleRemakeRequest);
        return ResultUtils.success(response);
    }

    /**
     * 查询 AI 人像风格重塑任务
     */
    @GetMapping("/image_restyle/get_task")
    public BaseResponse<GetImageRestyleTaskResponse> getImageRestyleTask(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetImageRestyleTaskResponse imageRestyleTask = aliYunAiReshapingImageApi.getImageRestyleTask(taskId);
        return ResultUtils.success(imageRestyleTask);
    }

    /**
     * 创建通用图像编辑任务
     */
    @PostMapping("/image_editing/create_task")
    public BaseResponse<CreateImageSynthesisTaskResponse> createGeneralImageEditing(
            @RequestBody CreateGeneralImageEditingRequest createGeneralImageEditingRequest) {
        if (createGeneralImageEditingRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        CreateImageSynthesisTaskResponse response = pictureService.createGeneralImageEditing(createGeneralImageEditingRequest);
        return ResultUtils.success(response);
    }

    /**
     * 查询通用图像编辑任务
     */
    @GetMapping("/image_editing/get_task")
    public BaseResponse<GetImageSynthesisTaskResponse> getGeneralImageEditing(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetImageSynthesisTaskResponse task = generalImageEditingApi.getImageSynthesisTask(taskId);
        
        // 如果任务失败，记录错误信息
        if (task.getOutput() != null && "FAILED".equals(task.getOutput().getTaskStatus())) {
            String errorCode = task.getOutput().getCode();
            String errorMsg = task.getOutput().getMessage();
            if (StrUtil.isNotBlank(errorCode)) {
                log.error("通用图像编辑任务失败，taskId: {}, code: {}, message: {}", 
                        taskId, errorCode, errorMsg);
            }
        }
        
        return ResultUtils.success(task);
    }

    /**
     * 创建线稿生图任务
     */
    @PostMapping("/doodle_painting/create_task")
    public BaseResponse<CreateDoodlePaintingTaskResponse> createDoodlePaintingTask(
            @RequestBody CreateDoodlePaintingRequest createDoodlePaintingRequest) {
        if (createDoodlePaintingRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        // 记录请求参数
        log.info("接收到线稿生图请求: prompt={}, sketchImageUrl={}, style={}",
                createDoodlePaintingRequest.getPrompt(),
                createDoodlePaintingRequest.getSketchImageUrl(),
                createDoodlePaintingRequest.getStyle());
                
        CreateDoodlePaintingTaskResponse response = pictureService.createDoodlePaintingTask(createDoodlePaintingRequest);
        return ResultUtils.success(response);
    }

    /**
     * 查询线稿生图任务
     */
    @GetMapping("/doodle_painting/get_task")
    public BaseResponse<GetDoodlePaintingTaskResponse> getDoodlePaintingTask(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetDoodlePaintingTaskResponse task = pictureDoodlePaintingApi.getDoodlePaintingTask(taskId);
        
        // 如果任务失败，记录错误信息
        if (task.getOutput() != null && "FAILED".equals(task.getOutput().getTaskStatus())) {
            String errorCode = task.getOutput().getCode();
            String errorMsg = task.getOutput().getMessage();
            if (StrUtil.isNotBlank(errorCode)) {
                log.error("线稿生图任务失败，taskId: {}, code: {}, message: {}", 
                        taskId, errorCode, errorMsg);
            }
        }
        
        return ResultUtils.success(task);
    }

}
